﻿using WebSocketApi.CacheManager;
using WebSocketApi.Interface;

namespace WebSocketApi;


/// <summary>
/// 缓存消息处理类 
/// </summary>
public class NoticeCacheHandler : INoticeCacheManager
{
    private readonly ICacheContext _cacheContext;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="cacheContext"></param>
    public NoticeCacheHandler(ICacheContext cacheContext)
    {
        _cacheContext = cacheContext;
    }

    /// <summary>
    /// 获取所有离线消息
    /// </summary>
    /// <param name="toUser">消息接收方</param>
    /// <returns></returns>
    public List<object> GetUserAllHistoryNotices(string toUser)
    {
        //消息缓存的格式: 接收者作为Key可快速搜索离线消息
        /*
         根据当前验证账号获取离线消息
         //存储的离线消息针对接收方，当接收方上线后，Socket服务自动推送
         以接收对象为Key，接收者上线后自动拉取 
         */
        try
        {
            var noticeAll = _cacheContext.GetCache<List<object>>(toUser);
            return noticeAll;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }

    /// <summary>
    /// 缓存离线消息
    /// </summary>
    /// <param name="toUser">接收者</param>
    /// <param name="message">消息内容</param>
    public void AddNotice(string toUser, object message)
    {
        var noticeList = GetUserAllHistoryNotices(toUser);
        if (noticeList != null)
        {
            noticeList.Add(message);
        }
        else
        {
            noticeList = new List<object>
            {
                message
            };
        }
        //覆盖缓存数据
        _cacheContext.SetCache(toUser, noticeList);
    }

    /// <summary>
    /// 缓存消息历史
    /// </summary>
    /// <param name="cacheKey">接收人</param>
    /// <param name="message">消息内容</param>
    public void AddNoticeRecord(string cacheKey, object message)
    {
        try
        {
            AddNotice(cacheKey, message);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }

    /// <summary>
    /// 删除缓存消息
    /// </summary>
    /// <param name="toUser"></param>
    public void RemoveNotice(string toUser)
    {
        try
        {
            _cacheContext.Remove(toUser);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }
}
